package com.connector.server.redis;

import redis.clients.jedis.JedisPubSub;
import redis.clients.jedis.Jedis;
import java.io.Serializable;

public class RedisSubscriber implements Runnable, Serializable
{
    private static final long serialVersionUID = 6625117171619814696L;
    private String channel;
    private Jedis jedis;
    private AbstractRedisPubSubListener pubSubLisener;
    private boolean flag;
    
    public void setJedis(final Jedis jedis) {
        this.jedis = jedis;
    }
    
    public RedisSubscriber(final String channel, final Jedis jedis, final AbstractRedisPubSubListener pubSubLisener) {
        this.flag = false;
        this.channel = channel;
        this.jedis = jedis;
        this.pubSubLisener = pubSubLisener;
    }
    
    public void start() {
        if (this.jedis == null) {
            throw new RuntimeException("---------------Redis启动异常---------------");
        }
        this.flag = true;
        this.jedis.subscribe((JedisPubSub)this.pubSubLisener, new String[] { this.channel });
    }
    
    public void stop() {
        if (this.jedis == null) {
            throw new RuntimeException("---------------Redis停止异常---------------");
        }
        this.pubSubLisener.unsubscribe(this.channel);
        this.jedis.close();
        this.flag = false;
    }
    
    public void restart(final Jedis jedis) {
        if (this.flag) {
            throw new RuntimeException("---------------此Redis监听器" + this.channel + "已经启动---------------");
        }
        this.setJedis(jedis);
        this.start();
    }
    
    @Override
    public void run() {
        this.start();
    }
}
